<?php
  include ("common/functions.php");
  include ("common/class.php");
  db_start();
  
  // Totals of User Bids
  $customerBids = new totalBids;

  userBids($customerBids,'wangguojianggg');
  
  ?>
  <head>
  <script type="text/javascript" src="https://www.google.com/jsapi"></script>
  <script type="text/javascript">
    google.load('visualization', '1', {'packages':['table']});
  </script>
  <?php $jsonObject = auctionsBidOn('test12345');?>
  <script type="text/javascript">
    function drawVisualization(){
      json = <?php echo $jsonObject?>;
      
      data = new google.visualization.DataTable(json, 0.5);
    
      visualization = new google.visualization.Table(document.getElementById('table'));
      var formatter = new google.visualization.ArrowFormat();
      formatter.format(data, 5);
      
      visualization.draw(data, {page: 'enable'});
    }
    google.setOnLoadCallback(drawVisualization);
  </script>
  </head>
  <body>
  <fieldset>
    <legend>Total Bids</legend>
    <div border='1'>Cash: <?php echo $customerBids->getTotalCash()?><br />Promo: <?php echo $customerBids->getTotalPromo()?><br />Total Bids: <?php echo $customerBids->getTotalBids()?></div>
  </fieldset>
  <fieldset>
    <legend>Available Bids</legend>
    <div border='1'>Cash: <?php echo $customerBids->getAvailableCash()?><br />Promo: <?php echo $customerBids->getAvailablePromo()?><br />Total Available: <?php echo $customerBids->getAvailable()?></div>
  </fieldset>
  <fieldset>
    <legend>Used Bids</legend>
    <div border='1'>Cash: <?php echo $customerBids->getUsedCash()?><br />Promo: <?php echo $customerBids->getUsedPromo()?><br />Total Used: <?php echo $customerBids->getUsed()?></div>
  </fieldset>

  <div id='table'></div>
  
  <?php productOverview(test12345); ?>
  <?php

  // Pulls information from the database and stores Bids in an object
  function userBids($bidsObject, $username){
    $query = "Select * from customer_bid_info where user_name = '{$username}'";
    $result = mysql_query($query);

    while($row = mysql_fetch_object($result)){
      // Setting Total Bids
	  $bidsObject->setTotal($row->total_bids, $row->total_purchase_bids, $row->total_bonus_bids);
  
      // Setting Available Bids
	  $bidsObject->totalAvailable($row->active_bids, $row->active_purchase_bids, $row->active_bonus_bids);
  
      // Setting Used Bids
	  $bidsObject->totalUsed(($row->total_bids - $row->active_bids), ($row->total_purchase_bids - $row->active_purchase_bids), ($row->total_bonus_bids - $row->active_bonus_bids));
    }
  }
  
  // Reports on the Auctions the User has won
  /*function auctionsWon($username){
    $query = "SELECT title, id, category_id, value_price, current_price FROM auctions WHERE status = 2 && winner = '{$username}'";
    $result = mysql_query($query);
    $num = 0;
    
    while($row = mysql_fetch_object($result)){
      // Queries the name of the category the product is in
      $query = "Select name from `category` where `id` = {$row->category_id}";
      $category = mysql_fetch_object(mysql_query($query));
      
      // Queries for the userId
      $query = "Select id from customer where user_name = '{$username}'";
      $user = mysql_fetch_object(mysql_query($query));
      
      // Queries the number of bids placed for auction
      $query = "Select * from bid_logs where customer_id = '{$user->id}' && auction_id = '{$row->id}'";
      $result2 = mysql_query($query);
      $numBids = mysql_num_rows($result2);
      
      // Finds total price paid for product
      $query = "Select total_price from orders where auction_id = '{$row->id}'";
      $totalPrice = mysql_fetch_object(mysql_query($query));
      
      // Sets the dynamic variable name
      $auction = "auction".$num;
      // Created a new object with variable name
      $$auction = new userAuctionsWon;
      
      // Loads information into each object
      $$auction->setAuctionDate($row->Last_Bid_Time);
      $$auction->setCategoryName($category->name);
      $$auction->setAuctionTitle($row->title);
      $$auction->setWinPrice($row->current_price);
      $$auction->setValuePrice($row->value_price);
      $$auction->setPricePaid($totalPrice->total_price);
      $$auction->setBidsPlaced($numBids);
      
      // Loads the array with the auctions objects
      $auctionsWon[] = $$auction;
      $num++;
    }
    return $auctionsWon;
  }*/
 
  // Function finds and reports the average bids and winning price for items the user has bid upon
  function auctionsBidOn($username){
    $query = "Select id from customer where user_name = '{$username}'";
    $user = mysql_fetch_object(mysql_query($query));
    
    $query = "Select count(*) as bids, auction_id from bid_logs where type=1 && customer_id = '{$user->id}' group by auction_id";
    $result = mysql_query($query);
    
    $jsonObject = "{
      cols: [{id: 'startDate', label: 'Start Date', type: 'datetime'},
            {id: 'category', label: 'Category Type', type: 'string'},
            {id: 'title', label: 'Auction Title', type: 'string'},
            {id: 'bids', label: 'Cash Bids', type: 'number'},
            {id: 'valuePrice', label: 'Value Price', type: 'number'},
            {id: 'roi', label: 'Return on Investment', type: 'number'}],
      rows: [";
    //number of bids they put on an auction is bids
    while($row = mysql_fetch_object($result)){
      $query = "Select start_time, category_id, title, value_price, winner from auctions where status=2 && id='{$row->auction_id}'";
      $auction = mysql_fetch_object(mysql_query($query));
      
      $query = "Select name from category where id='{$auction->category_id}'";
      $category = mysql_fetch_object(mysql_query($query));
      
      //cash bids ROI (return on investment);
      if($auction->value_price!=0){
        $cash_bids_spent = $row->bids*0.6;
        $roi = (($auction->value_price - $cash_bids_spent) - $cash_bids_spent) / $cash_bids_spent;
        if($username != $auction->winner){
          if($roi > 0)
            $roi = "-".$roi;
        }
        $title = str_replace("'", "\'", $auction->title);
        $Date = date("Y",$auction->start_time);
        $Date = $Date.",".(date("n",$auction->start_time)-1);
        $Date = $Date.date(",j,G,i,s",$auction->start_time);
        echo $Date."<br>";
        
        $jsonObject .= "{c:[
          {v: new Date(".$Date."), f: '".date("F j, Y",$auction->start_time)."'},
          {v: '".$category->name."'},
          {v: '".$title."'}, 
          {v: ".$row->bids."}, 
          {v: ".$auction->value_price.", f: '$".number_format($auction->value_price,2)."'}, 
          {v: ".$roi.", f: '".number_format($roi,2)."%'}]},";
      }
    }
    $jsonObject .= "]};";
    echo $jsonObject;
    return $jsonObject;
  }
  
  function productOverview($username){
    $query = "Select id from customer where user_name = '{$username}'";
    $user = mysql_fetch_object(mysql_query($query));
    
    $query = "Select count(*) as bids, auction_id from bid_logs where type=1 && customer_id = '{$user->id}' group by auction_id";
    $result = mysql_query($query);
    
    $jsonObject = "{
      cols: [{id: 'category', label: 'Category Type', type: 'string'},
            {id: 'title', label: 'Auction Title', type: 'string'},
            {id: 'bids', label: 'Cash Bids', type: 'number'},
            {id: 'valuePrice', label: 'Value Price', type: 'number'},
            {id: 'roi', label: 'Return on Investment', type: 'number'}],
      rows: [";
    while($row = mysql_fetch_object($result)){
      $query = "Select product_id, value_price, winner from auctions where status=2 && id='{$row->auction_id}' group by product_id";
      $auction = mysql_fetch_object(mysql_query($query));
      
      $query = "Select name from category where id='{$auction->category_id}'";
      $category = mysql_fetch_object(mysql_query($query));
      
      $query = "Select title from products where id='{$auction->product_id}'";
      $product = mysql_fetch_object(mysql_query($query));
      
      if(empty($products) || !in_array($product->title, $products[0])){
        $products[0][] = $product->title;
        $products[1][] = $row->bids;
      }else if(in_array($product->title, $products[0])){
        $num = array_search($product->title, $products[0]);
        $products[1][$num] = $row->bids + $products[1][$num];
      }
      $jsonObject .= "{c:[
          {v: '".$category->name."'},
          {v: '".$title."'}, 
          {v: ".$row->bids."}, 
          {v: ".$auction->value_price.", f: '$".number_format($auction->value_price,2)."'}, 
          {v: ".$roi.", f: '".number_format($roi,2)."%'}]},";
    }
    /*foreach($products as $value)
      echo $value."<br>";*/
  }
?>